package web.suzy.oj.manager.file;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import web.suzy.oj.common.exception.StatusFailException;
import web.suzy.oj.common.exception.StatusSystemErrorException;
import web.suzy.oj.dao.common.FileEntityService;
import web.suzy.oj.dao.user.SysUserRoleEntityService;
import web.suzy.oj.dao.user.UserInfoEntityService;
import web.suzy.oj.pojo.entity.user.SysRole;
import web.suzy.oj.pojo.entity.user.UserInfo;
import web.suzy.oj.pojo.vo.SysUserRoleVO;
import web.suzy.oj.shiro.AccountProfile;
import web.suzy.oj.utils.Constants;

import java.io.File;
import java.util.Map;

/**
 * YangSuzy 软件工作室
 * 类名: ImageManager
 * 描述: ---- 待定 -----
 * 功能: ---- 待定 -----
 * ========上线后需修改部分代码=========
 *
 * @author YangSuzy
 * Date: 2022/11/30 11:19
 */
@Component
@Slf4j(topic = "suzyoj")
public class ImageManager {
    @Autowired
    private FileEntityService fileEntityService;

    @Autowired
    private UserInfoEntityService userInfoEntityService;

    @Autowired
    private SysUserRoleEntityService userRoleEntityService;

    /**
     * 方法名: uploadAvatar
     * 描述: 上传头像
     *
     * @param image 头像图片
     * @return java.util.Map<java.lang.Object, java.lang.Object>
     * @date 2022/11/30 11:20
     * @auther YangSuzy
     **/
    @Transactional(rollbackFor = Exception.class)
    public Map<Object, Object> uploadAvatar(MultipartFile image) throws StatusFailException, StatusSystemErrorException {
        if (image == null) {
            throw new StatusFailException("上传的头像图片文件不能为空！");
        }
        if (image.getSize() > 1024 * 1024 * 2) {
            throw new StatusFailException("上传的头像图片文件大小不能大于2M！");
        }
        //获取文件后缀
        String suffix = image.getOriginalFilename().substring(image.getOriginalFilename().lastIndexOf(".") + 1);
        if (!"jpg,jpeg,gif,png,webp".toUpperCase().contains(suffix.toUpperCase())) {
            throw new StatusFailException("请选择以下格式的头像图片！[jpg, jpeg, gif, png, webp]");
        }
        //若不存在该目录，则创建目录
        FileUtil.mkdir(Constants.File.USER_AVATAR_FOLDER.getPath());
        //通过UUID生成唯一文件名
        String filename = IdUtil.simpleUUID() + "." + suffix;

        //将文件保存到指定目录
        File newFile = FileUtil.file(Constants.File.USER_AVATAR_FOLDER.getPath() + File.separator + filename);
        try {
            /**
             * 上线后需修改
             */
            image.transferTo(newFile.getAbsoluteFile());
        } catch (Exception e) {
            log.error("头像文件上传异常-------------->", e);
            throw new StatusSystemErrorException("服务器异常：头像上传失败！");
        }

        // 获取当前登录用户
        AccountProfile accountProfile = (AccountProfile) SecurityUtils.getSubject().getPrincipal();
        // 将当前用户所属的file表中avatar类型的实体的delete设置为1；
        fileEntityService.updateFileToDeleteByUidAndType(accountProfile.getUid(), "avatar");

        //更新user_info中的avatar
        UpdateWrapper<UserInfo> userInfoUpdateWrapper = new UpdateWrapper<>();
        userInfoUpdateWrapper.set("avatar", Constants.File.IMG_API.getPath() + filename)
                .eq("uuid", accountProfile.getUid());
        userInfoEntityService.update(userInfoUpdateWrapper);

        //插入file表记录
        web.suzy.oj.pojo.entity.common.File imgFile = new web.suzy.oj.pojo.entity.common.File();
        imgFile.setName(filename)
                .setFolderPath(Constants.File.USER_AVATAR_FOLDER.getPath())
                .setFilePath(Constants.File.USER_AVATAR_FOLDER.getPath() + File.separator + filename)
                .setSuffix(suffix)
                .setType("avatar")
                .setUid(accountProfile.getUid());
        fileEntityService.saveOrUpdate(imgFile);
        // 更新session
        accountProfile.setAvatar(Constants.File.IMG_API.getPath() + filename);

        //获取用户角色信息
        SysUserRoleVO userRolesVo = userRoleEntityService.getUserRoles(accountProfile.getUid(), null);

        return MapUtil.builder()
                .put("uid", userRolesVo.getUid())
                .put("username", userRolesVo.getUsername())
                .put("nickname", userRolesVo.getNickname())
                .put("avatar", Constants.File.IMG_API.getPath() + filename)
                .put("email", userRolesVo.getEmail())
                .put("grade", userRolesVo.getGrade())
                .put("course", userRolesVo.getCourse())
                .put("classes", userRolesVo.getClasses())
                .put("number", userRolesVo.getNumber())
                .put("signature", userRolesVo.getSignature())
                .put("realname", userRolesVo.getRealname())
                .put("roleList", userRolesVo.getRoles().stream().map(SysRole::getRole))
                .map();
    }

    /**
     * 方法名: uploadCarouselImg
     * 描述: 上传主页轮播图
     *
     * @param image 图片文件
     * @return java.util.Map<java.lang.Object, java.lang.Object>
     * @date 2022/11/30 11:33
     * @auther YangSuzy
     **/
    @Transactional(rollbackFor = Exception.class)
    public Map<Object, Object> uploadCarouselImg(MultipartFile image) throws StatusFailException, StatusSystemErrorException {
        if (image == null) {
            throw new StatusFailException("上传的图片文件不能为空！");
        }
        //获取文件后缀
        String suffix = image.getOriginalFilename().substring(image.getOriginalFilename().lastIndexOf(".") + 1);
        if (!"jpg,jpeg,gif,png,webp,jfif,svg".toUpperCase().contains(suffix.toUpperCase())) {
            throw new StatusFailException("请选择以下格式的图片！[jpg, jpeg, gif, png, webp, jfif, svg]");
        }
        //若不存在该目录，则创建目录
        FileUtil.mkdir(Constants.File.HOME_CAROUSEL_FOLDER.getPath());
        //通过UUID生成唯一文件名
        String filename = IdUtil.simpleUUID() + "." + suffix;
        //将文件保存指定目录
        File newFile = FileUtil.file(Constants.File.HOME_CAROUSEL_FOLDER.getPath() + File.separator + filename);
        try {
            /**
             * 上线后需修改
             */
            image.transferTo(newFile.getAbsoluteFile());
        } catch (Exception e) {
            log.error("图片文件上传异常-------------->{}", e.getMessage());
            throw new StatusSystemErrorException("服务器异常：图片上传失败！");
        }

        // 获取当前登录用户
        AccountProfile userRolesVo = (AccountProfile) SecurityUtils.getSubject().getPrincipal();

        // 插入file表记录
        web.suzy.oj.pojo.entity.common.File imgFile = new web.suzy.oj.pojo.entity.common.File();
        imgFile.setName(filename)
                .setFolderPath(Constants.File.HOME_CAROUSEL_FOLDER.getPath())
                .setFilePath(Constants.File.HOME_CAROUSEL_FOLDER.getPath() + File.separator + filename)
                .setSuffix(suffix)
                .setType("carousel")
                .setUid(userRolesVo.getUid());
        fileEntityService.saveOrUpdate(imgFile);

        return MapUtil.builder()
                .put("id", imgFile.getId())
                .put("url", Constants.File.IMG_API.getPath() + filename)
                .map();
    }
}
